package com.unionftech.common.base.mvp.impl

import com.unionftech.common.base.mvp.IBasePresenter
import com.unionftech.common.base.mvp.IBaseView
import java.lang.ref.WeakReference
import java.lang.reflect.ParameterizedType


abstract class BasePresenter<V : IBaseView, M : BaseModel> : IBasePresenter {
    private lateinit var weakReference: WeakReference<IBaseView>
    private lateinit var mModel: M
    override fun attach(view: IBaseView) {
        weakReference = WeakReference(view)
        //通过获得泛型类的父类，拿到泛型接口类实例，通过反射实例化model
        val type = this.javaClass.genericSuperclass as ParameterizedType
        val types = type.actualTypeArguments
        try {
            mModel = (types[1] as Class<*>).newInstance() as M
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    protected fun getView(): V? {
        return weakReference.get() as V?
    }

    protected fun getModel(): M {
        return mModel
    }

    override fun detach() {
        weakReference.clear()
        mModel.detach()
    }
}